package com.android.tea.adapter;

import java.util.Collections;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.android.tea.R;
import com.android.tea.TeaFriendDetailActivity;
import com.android.tea.entity.TeaFriend;
import com.android.tea.entity.TeaFriend.FriendType;
import com.android.tea.image.ImageLoaderManager;
import com.android.tea.util.PinyinComparator;
import com.android.tea.util.StringUtils;
import com.android.tea.util.Utils;

public class ChartAdapter extends BaseAdapter implements SectionIndexer{

	private static final String TAG = "ChartAdapter";
	private LayoutInflater inflater;
	private List<TeaFriend> list;
	private Context context;
	private ImageLoaderManager imageLoaderManager;
	
	public ChartAdapter(Context context,List<TeaFriend> list) {
		super();
		this.context = context;
		this.list = list;
		Collections.sort(list, new PinyinComparator());
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageLoaderManager = new ImageLoaderManager(context, new Handler(), this);
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public TeaFriend getItem(int position) {
		if (getCount() >= position + 1) {
			return list.get(position);
		} else {
			return null;
		}
	}

	@Override
	public long getItemId(int position) {
		TeaFriend item = getItem(position);
		if (item != null) {
			return item.getId();
		} else {
			return 0;
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final TeaFriend teaFriend = list.get(position);
		Log.i(TAG, "list size is " + list.size());
		if (teaFriend == null) {
			return null;
		}
		final ViewHolder holder;
		if (convertView == null) {	
			convertView = inflater.inflate(R.layout.contact_item, null);
			holder = new ViewHolder();
			holder.item = (LinearLayout) convertView.findViewById(R.id.contactitem_layout);
			holder.title = (TextView)convertView.findViewById(R.id.contactitem_catalog);
			holder.ivAvatar = (ImageView) convertView.findViewById(R.id.contactitem_avatar_iv);
			holder.tvTitle = (TextView) convertView.findViewById(R.id.contactitem_nick);
			holder.tvChart = (TextView) convertView.findViewById(R.id.contactitem_select_cb);
			holder.id = position;
			convertView.setTag(holder);
		}else {
			holder = (ViewHolder) convertView.getTag();
		}
		OnClickListener clickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.contactitem_layout:
					Intent intent = new Intent(context,TeaFriendDetailActivity.class);
					intent.putExtra("contactid", teaFriend.getId());
					context.startActivity(intent);
					break;
				case R.id.contactitem_avatar_iv:
					
					break;
				default:
					break;
				}
			}

			
		};
		
		holder.item.setOnClickListener(clickListener);
		holder.ivAvatar.setOnClickListener(clickListener);
		setData(teaFriend,holder,position);
		return convertView;
	}

	private void setData(TeaFriend teaMember, ViewHolder holder, int position) {
		String catalog = converterToFirstSpell(teaMember.getTitle()).substring(0, 1);
		if(position == 0){
			holder.title.setVisibility(View.VISIBLE);
			holder.title.setText(catalog);
		}else{
			String lastCatalog = converterToFirstSpell(list.get(position-1).getTitle()).substring(0, 1);
			if(catalog.equals(lastCatalog)){
				holder.title.setVisibility(View.GONE);
			}else{
				holder.title.setVisibility(View.VISIBLE);
				holder.title.setText(catalog);
			}
		}
		
		FriendType type = teaMember.getType();
		if(FriendType.Star_Friend==type) {
			holder.title.setText(context.getResources().getString(R.string.star_friend_title));
			setImage(holder.ivAvatar,R.drawable.tea_team);
			setTitle(holder.tvTitle,context.getResources().getString(R.string.tea_team));
			setDynamic(holder.tvChart,teaMember != null ? teaMember.getDesc():null);
		}else {
			String title = teaMember.getTitle();
			setImage(holder.ivAvatar,teaMember.getAvatar());
			setTitle(holder.tvTitle,title);
			setDynamic(holder.tvChart,teaMember != null ? teaMember.getDesc():null);
		}
	}
	private void setDynamic(TextView tvTime, String dynamic) {
		Log.i(TAG, "dynamic is " + dynamic);
		if (StringUtils.isNotNullOrEmpty(dynamic)) {
			tvTime.setText(dynamic);
		}else {
			tvTime.setText("");
		}
	}

	private void setImage(ImageView ivAvatar, String avatar) {
		if (StringUtils.isNotNullOrEmpty(avatar)) {
			ivAvatar.setImageBitmap(imageLoaderManager.getImage(avatar, R.drawable.tea_default,
					Utils.dipToPixels(context, 74)));
		} else {
			ivAvatar.setImageResource(R.drawable.tea_default);
		}
	}
	private void setImage(ImageView ivAvatar, int resId) {
		ivAvatar.setImageResource(resId);
	}

	private void setTitle(TextView tvTitle, String title) {
		Log.i(TAG, "title is " + title);
		if (StringUtils.isNotNullOrEmpty(title)) {
			tvTitle.setText(title);
		}else {
			tvTitle.setText(context.getResources().getString(R.string.unknown));
		}
	}
	static class ViewHolder {
		int id;
		LinearLayout item;
//		ImageView start;
		TextView title;
		
		ImageView ivAvatar;
		TextView tvTitle;
		TextView tvChart;
	}
	@Override
	public int getPositionForSection(int section) {
		for (int i = 0; i < list.size(); i++) {  
            String l = converterToFirstSpell(list.get(i).getTitle()).substring(0, 1);  
            char firstChar = l.toUpperCase().charAt(0);  
            if (firstChar == section) {  
                return i;  
            }  
        } 
		return -1;
	}
	@Override
	public int getSectionForPosition(int position) {
		return 0;
	}
	@Override
	public Object[] getSections() {
		return null;
	}
	
	/**  
     * 汉字转换位汉语拼音首字母，英文字符不变  
     * @param chines 汉字  
     * @return 拼音  
     */     
    public static String converterToFirstSpell(String chines){             
         String pinyinName = "";      
        char[] nameChar = chines.toCharArray();      
         HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();      
         defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);      
         defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);      
        for (int i = 0; i < nameChar.length; i++) {      
            if (nameChar[i] > 128) {      
                try {      
                     pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);      
                 } catch (BadHanyuPinyinOutputFormatCombination e) {      
                     e.printStackTrace();      
                 }      
             }else{      
                 pinyinName += nameChar[i];      
             }      
         }      
        return pinyinName;      
     }      
}
